﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;

namespace Trade.Library.Data
{
    /// <summary>
    /// 
    /// </summary>
    public class Transaction : IDisposable
    {
        private IDbConnection _conn = null;
        private IDbTransaction _tran = null;
        /// <summary>
        /// 构造事务
        /// </summary>
        /// <param name="conn"></param>
        public Transaction(IDbConnection conn)
        {
            _conn = conn;
            _tran = _conn.BeginTransaction();
        }
        /// <summary>
        /// 获取开启的事务
        /// </summary>
        public IDbTransaction tran
        {
            get { return _tran; }
        }
        /// <summary>
        /// 获取开启的连接
        /// </summary>
        public IDbConnection conn
        {
            get { return _conn; }
        }
        /// <summary>
        /// 提交事务
        /// </summary>
        public void Commit()
        {
            if (_conn == null || _tran == null)
            {
                this.Dispose();
                throw new Exception("连接无效");
            }
            _tran.Commit();
            this.Dispose();
        }
        /// <summary>
        /// 回滚事务
        /// </summary>
        public void Rollback()
        {
            if (_conn == null || _tran == null)
            {
                this.Dispose();
                throw new Exception("连接无效");
            }
            _tran.Rollback();
            this.Dispose();
        }
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (_conn != null)
            {
                _conn.Close();
                _conn.Dispose();
                _conn = null;
            }
            if (_tran != null)
            {
                _tran.Dispose();
                _tran = null;
            }
        }
    }
}
